﻿using System.Timers;

namespace cz.zcu.PreSti.Components
{
    public class Repeater : RunnableComponent
    {
        private int repetitionRate = 0;
        private int repetition = 0;
        public Repeater(IPresentation p) : base(p, 1, 1, 2, 1)
        {
            runTimer.Elapsed += new ElapsedEventHandler(timeElapsed);
        }

        public int RepetitionRate
        {
            get
            {
                return repetitionRate;
            }
            set
            {
                repetitionRate = value;
            }
        }

        public override void update() { }

        public override void trigIn(int n)
        {          
            trigOut();
        }

        public void trigOut()
        {
            this.retrieveValuesFromGetters();         
            if (repetitionRate <= 0) return;
            runTimer.Interval = delay;
            if (repetition < repetitionRate)
            {
                repetition++;
                trigOut(0);
                if (delay > 0) runTimer.Start(); else trigOut();
            }
        }

        private new void timeElapsed(object sender, ElapsedEventArgs e)
        {
            trigOut();
        }

        public override void setValueToSetter(int setterN, object value)
        {
            switch (setterN)
            {
                case 1:
                    convertValue(ref repetitionRate, value); break;
                default:
                    base.setValueToSetter(setterN, value); break;
            }
        }

        public override object getValueFromGetter(int getterN)
        {
            switch (getterN)
            {
                case 0:
                    return repetition;
                default:
                    return base.getValueFromGetter(getterN);
            }
        }
    }
}
